package cn.frank.framework.king.conf.exception;

import cn.frank.framework.king.domain.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Objects;


/**
 * 全局异常
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler(){
    }

    /**
     * 拦截JSON参数校验
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BindException.class)
    public Result<String> bindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String msg;
        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null) {
            msg = fieldError.getField() + "属性，" + fieldError.getDefaultMessage();
        } else {
            msg = "参数校验失败";
        }
        log.error(msg, e);
        return Result.fail(msg);
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Object> ParamException(HttpMessageNotReadableException e) {
        String msg = "传递表单参数格式不正确";
        log.error(msg, e);
        return Result.fail("传递表单参数格式不正确");
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> handleException(Exception e) {
        log.error("CONSOLE", e);
        String msg = "全局异常";
        log.error(msg, e);
        return Result.fail(e.getLocalizedMessage());
    }

}